//
//  CacheDaoForStadiumsInfo.m
//  GolfFriend
//
//  Created by Vescky on 13-12-13.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "CacheDaoForStadiumsInfo.h"

#define TB_CACHE_STADIUMS @"tb_cache_stadiums"

@implementation CacheDaoForStadiumsInfo

static CacheDaoForStadiumsInfo *defaultStadiumCache;

+ (id)shareCacheDaoForStadiumsInfo {
    if (!defaultStadiumCache) {
        defaultStadiumCache = [[CacheDaoForStadiumsInfo alloc] init];
        DB *dbase = [[DB alloc] init];
        FMDatabase *database = [dbase getDatabase];
        [database executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(recordId integer primary key,status text,content text)",TB_CACHE_STADIUMS]];
        [database close];
    }
    return defaultStadiumCache;
}

// -- recordId
// -- content
- (bool)saveStadiumInfo:(NSDictionary*)dict {
    if (!dict || [dict count] < 2) {
        return NO;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:dict];

    if (!params || [params count] < 1) {
        return NO;
    }
    
    if ([self ifRecordExist:[dict objectForKey:@"recordId"]]) {
        [self update:params where:[[NSMutableDictionary alloc] initWithObjectsAndKeys:[dict objectForKey:@"recordId"],@"recordId", nil] inTable:TB_CACHE_STADIUMS];
    }
    else {
        [self insert:params inTable:TB_CACHE_STADIUMS];
    }
    
    return YES;
}

- (bool)saveStadiums:(NSMutableArray*)sArr {
    if (!sArr || [sArr count] < 1) {
        return NO;
    }
    
    for (int i = 0; i < [sArr count]; i++) {
        [self saveStadiumInfo:[sArr objectAtIndex:i]];
    }
    
    return YES;
}

- (NSMutableArray*)getStadiums:(NSRange)lRange {
//    [self deleteInvalidData];
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where status = '1'",TB_CACHE_STADIUMS];
    NSMutableArray *allData = [self queryByConfition:qConfition];//[self queryAll:TB_CACHE_STADIUMS];
//    allData = [self queryByConfition:@"and status = '1'"];
    NSMutableArray *arrLimitted = [[NSMutableArray alloc] init];
    if ([allData count] > lRange.length) {
        arrLimitted = [[NSMutableArray alloc] initWithArray:[allData subarrayWithRange:lRange]];
    }
    else {
        arrLimitted = [[NSMutableArray alloc] initWithArray:allData];
    }
    return arrLimitted;
}


#pragma - Private
- (bool)ifRecordExist:(NSString*)rId {
    if (!rId || rId.length < 1) {
        return NO;
    }
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where recordId = '%@'",TB_CACHE_STADIUMS,rId];
    NSMutableArray *arr = [self queryByConfition:qConfition];
    if (arr && [arr count] > 0) {
        return YES;
    }
    return NO;
}

- (void)deleteInvalidData {
    [self remove:@"status" is:@"-1" inTable:TB_CACHE_STADIUMS];
    [self remove:@"status" is:@"0" inTable:TB_CACHE_STADIUMS];
}

@end
